package com.ai.common.utils;

import com.ai.common.enums.ConfigModuleEnum;
import com.ai.sevice.config.response.dto.AiCardCategoryDto;
import com.ai.sevice.config.response.dto.AiCardDto;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class CommonUtil {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(generateRandomCode(6));
        }
    }

    /**
     * 获取验证码key
     * @param activityNo
     * @param uid
     * @return
     */
    public static String getWelfareBucketKey(String activityNo,String uid) {
        return "welfare-" + activityNo + "-" + uid;
    }

    /**
     * 获取验证码key
     * @param type
     * @param phone
     * @return
     */
    public static String getVerificationCodeKey(Integer type,String phone) {
        return "sendVerificationCode-" + type + "-" + phone;
    }

    /**
     * 生成指定长度的随机数字验证码
     * @return
     */
    public static String generateRandomCode(int codeLength) {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < codeLength; i++) {
            code.append(random.nextInt(10)); // 生成0-9之间的随机整数
        }
        return code.toString();
    }

    /**
     * 获取当天日期字符串
     * @return
     */
    public static String getNowDateStr(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }

    /**
     * 计算涨跌幅
     * @param numberStart 开始数字
     * @param numberEnd 结束数字
     * @return
     */
    public static BigDecimal calculatePercent(BigDecimal numberStart,BigDecimal numberEnd){
        if (numberStart == null || numberEnd == null){
            return new BigDecimal(0);
        }
        BigDecimal change = numberEnd.subtract(numberStart);
        //小数点后面为0则去掉
        BigDecimal changePercent = change.divide(numberStart, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros();
        return changePercent;
    }

    public static BigDecimal getZtPrice(BigDecimal preClose,String symbol){
        if (preClose == null || StringUtils.isBlank(symbol)){
            return null;
        }
        String symbolNumber = getSymbolNumber(symbol);
        String exchange = getExchange(symbol);
        if (StringUtils.isBlank(symbolNumber) || StringUtils.isBlank(exchange)){
            return null;
        }
        if (symbolNumber.startsWith("30") || symbolNumber.startsWith("688")) {
            //创业板 20% 科创板 20%
            //preClose * (1 + 0.2)
            BigDecimal limitUp = preClose.multiply(new BigDecimal("1.2"));
            return limitUp.setScale(2, BigDecimal.ROUND_HALF_UP);
        }else if (symbolNumber.startsWith("43") || symbolNumber.startsWith("83") || symbolNumber.startsWith("87") || symbolNumber.startsWith("88")){
            //北证 30%
            //preClose * (1 + 0.3)
            BigDecimal limitUp = preClose.multiply(new BigDecimal("1.3"));
            return limitUp.setScale(2, BigDecimal.ROUND_HALF_UP);
        }else{
            //preClose * (1 + 10%)
            BigDecimal limitUp = preClose.multiply(new BigDecimal("1.1"));
            return limitUp.setScale(2, BigDecimal.ROUND_HALF_UP);
        }

//        //preClose * (1 + 5%)
//        BigDecimal limitUp = preClose.multiply(new BigDecimal("1.05"));
//        return limitUp.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public static BigDecimal getDtPrice(BigDecimal preClose,String symbol){
        if (preClose == null || StringUtils.isBlank(symbol)){
            return null;
        }
        String symbolNumber = getSymbolNumber(symbol);
        String exchange = getExchange(symbol);
        if (StringUtils.isBlank(symbolNumber) || StringUtils.isBlank(exchange)){
            return null;
        }
        if (symbolNumber.startsWith("30") || symbolNumber.startsWith("688")) {
            //创业板 20% 科创板 20%
            //preClose * (1 - 0.2)
            BigDecimal limitDown = preClose.multiply(new BigDecimal("0.8"));
            return limitDown.setScale(2, BigDecimal.ROUND_HALF_UP);
        }else if (symbolNumber.startsWith("43") || symbolNumber.startsWith("83") || symbolNumber.startsWith("87") || symbolNumber.startsWith("88")){
            //北证 30%
            //preClose * (1 - 0.3)
            BigDecimal limitDown = preClose.multiply(new BigDecimal("0.7"));
            return limitDown.setScale(2, BigDecimal.ROUND_HALF_UP);
        }else{
            //preClose * (1 - 10%)
            BigDecimal limitDown = preClose.multiply(new BigDecimal("0.9"));
            return limitDown.setScale(2, BigDecimal.ROUND_HALF_UP);
        }
//        //preClose * (1 - 5%)
//        BigDecimal limitDown = preClose.multiply(new BigDecimal("0.95"));
//        return limitDown.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 获取股票数字代码
     * @param symbol
     * @return
     */
    public static String getSymbolNumber(String symbol){
        if (StringUtils.isBlank(symbol)){
            return null;
        }
        //获取字符串中的数字
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(symbol);
        StringBuilder symbolNumber = new StringBuilder();
        while (matcher.find()) {
            symbolNumber.append(matcher.group());
        }
        return symbolNumber.toString();
    }
    /**
     * 获取交易所代码
     * @param symbol
     * @return
     */
    public static String getExchange(String symbol){
        if (StringUtils.isBlank(symbol)){
            return null;
        }
        String exchange = symbol.replaceAll("\\d", "");
        return exchange;
    }

    /**
     * 获取日期时间戳
     * @param dateStr
     * @return
     */
    public static long getDateTimestamp(String dateStr){
        if (StringUtils.isBlank(dateStr)){
            return 0;
        }
        try {
            return new SimpleDateFormat("yyyy-MM-dd").parse(dateStr).getTime();
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return 0;
    }

    /**
     * 获取日期时间时间戳
     * @param dateTimeStr
     * @return
     */
    public static long getDateTimeTimestamp(String dateTimeStr){
        if (StringUtils.isBlank(dateTimeStr)){
            return 0;
        }
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateTimeStr).getTime();
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return 0;
    }

    /**
     * 获取日期时间字符串
     * @param dateTimestamp
     * @return
     */
    public static String getDateTimeStr(Long dateTimestamp){
        if (dateTimestamp == null){
            return null;
        }
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dateTimestamp));
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * 获取日期时间字符串
     * @param dateTimestamp
     * @return
     */
    public static String getDateTimeStr2(Long dateTimestamp){
        if (dateTimestamp == null){
            return null;
        }
        try {
            return new SimpleDateFormat("yyyy-MM-dd").format(new Date(dateTimestamp));
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * 获取数字单位
     * @param number 数字
     * @return
     */
    public static String getNumberUnit(BigDecimal number) {
        return getNumberUnit(number,null);
    }

    /**
     * 获取数字单位
     * @param number 数字
     * @param divisor 除数
     * @return
     */
    public static String getNumberUnit(BigDecimal number,BigDecimal divisor){
        if (number == null){
            return null;
        }
        if (number.compareTo(new BigDecimal(0)) == 0){
            return "0";
        }
        if (divisor != null){
            number = number.divide(divisor, 2, RoundingMode.HALF_UP);
        }
        String resultStr = null;
        BigDecimal tenThousand = new BigDecimal("10000");
        BigDecimal threshold = new BigDecimal("-10000");
        BigDecimal yi = new BigDecimal("100000000");
        BigDecimal fuYi = new BigDecimal("-100000000");
        if (number.compareTo(yi) >= 0) {
            BigDecimal result = number.divide(yi, 2, RoundingMode.HALF_UP);
            result = result.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
            resultStr = result.toPlainString() + "亿";
        }else if (number.compareTo(tenThousand) >= 0) {
            BigDecimal result = number.divide(tenThousand,2,RoundingMode.HALF_UP);
            //stripTrailingZeros如果小数点后面为0，则去掉小数点
            result = result.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
            //toPlainString去掉指数字段
            resultStr = result.toPlainString() + "万";
        } else if (number.compareTo(fuYi) < 0) {
            BigDecimal result = number.divide(new BigDecimal("100000000"),2,BigDecimal.ROUND_HALF_DOWN).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            //stripTrailingZeros如果小数点后面为0，则去掉小数点
            result = result.setScale(2, RoundingMode.HALF_DOWN).stripTrailingZeros();
            //toPlainString去掉指数字段
            resultStr = result.toPlainString() + "亿";
        } else if (number.compareTo(threshold) < 0) {
            BigDecimal result = number.divide(new BigDecimal("10000"),2,BigDecimal.ROUND_HALF_DOWN).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            //stripTrailingZeros如果小数点后面为0，则去掉小数点
            result = result.setScale(2, RoundingMode.HALF_DOWN).stripTrailingZeros();
            //toPlainString去掉指数字段
            resultStr = result.toPlainString() + "万";
        } else {
            resultStr = number.toString();
        }
        return resultStr;
    }

    public static AiCardDto getAiCardByType(String optionType){
        if (StringUtils.isBlank(optionType)){
            return null;
        }
        String cardListStr = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "cardList");
        if (StringUtils.isNotBlank(cardListStr)){
            List<AiCardCategoryDto> cardCategoryList = JSON.parseArray(cardListStr,AiCardCategoryDto.class);
            if (CollectionUtils.isEmpty(cardCategoryList)){
                return null;
            }
            for (AiCardCategoryDto aiCardCategoryDto : cardCategoryList){
                if (CollectionUtils.isEmpty(aiCardCategoryDto.getCardList())){
                    continue;
                }
                Optional<AiCardDto> first = aiCardCategoryDto.getCardList().stream().filter(x -> x.getOptionType().equals(optionType)).findFirst();
                if (first.isPresent()){
                    return first.get();
                }
            }
        }
        return null;
    }
}
